package com.mmlc.meimei.lichengkongjian.classify;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;

import com.androidnetframe.utils.LogUtils;
import com.mmlc.meimei.lichengkongjian.R;
import com.mmlc.meimei.lichengkongjian.brand.BrandInfoActivity;
import com.mmlc.meimei.lichengkongjian.jsbridge.BridgeHandler;
import com.mmlc.meimei.lichengkongjian.jsbridge.BridgeWebView;
import com.mmlc.meimei.lichengkongjian.jsbridge.CallBackFunction;
import com.mmlc.meimei.lichengkongjian.jsbridge.DefaultHandler;
import com.mmlc.meimei.lichengkongjian.mine.RegisterAccount;
import com.mmlc.utils.Constants;
import com.mmlc.utils.ToastUtils;
import com.mmlc.utils.ViewUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;

import butterknife.ButterKnife;

/**
 * Created by Administrator on 2016/12/6.
 */
public class FastGoodsDetailFragment extends LazyFragment {

    BridgeWebView webView;
    // 标志位，标志已经初始化完成。
    private boolean isPrepared;
    String url;
    View view;
    boolean isFirstInit = true;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        getActivity().getWindow().addFlags(
                WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
        if(view == null) {
            view = inflater.inflate(R.layout.fragment_fastgoodswebview, container, false);
        }
        //XXX初始化view的各控件
        webView = (BridgeWebView)view.findViewById(R.id.webview);
        initView();
        isFirstInit = true;
        isPrepared = true;
        lazyLoad();
        return view;
    }

    @Override
    protected void lazyLoad() {
        if(!isPrepared || !isVisible) {
            return;
        }
        if(isFirstInit) {
            if (!ViewUtils.isEmpty(url))
                webView.loadUrl(url);
            else
                ToastUtils.showToast("网络请求有误");
            isFirstInit = false;
        }
    }

    public void initView() {
        final Bundle bundle = getArguments();
        url = bundle.getString("type", "");
        webView.setDefaultHandler(new DefaultHandler());
        webView.getSettings().setJavaScriptEnabled(true);//是否允许执行js，默认为false。设置true时，会提醒可能造成XSS漏洞
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);//设置js可以直接打开窗口，如window.open()，默认为false
        webView.setWebChromeClient(new WebChromeClient());
        webView.getSettings().setSupportZoom(true);//是否可以缩放，默认true
        webView.getSettings().setDisplayZoomControls(true);
//        webView.getSettings().setBuiltInZoomControls(true);//是否显示缩放按钮，默认false
        webView.getSettings().setUseWideViewPort(true);//设置此属性，可任意比例缩放。大视图模  式
        webView.getSettings().setUserAgentString(webView.getSettings().getUserAgentString() + "mmlc.meiqi");
        webView.getSettings().setLoadWithOverviewMode(true);//和setUseWideViewPort(true)一起解决网页自适应问题
        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
        webView.getSettings().setAppCacheEnabled(true);//是否使用缓存
        webView.getSettings().setAppCachePath(Constants.DIR_CACHE);
        webView.getSettings().setAllowFileAccess(true);
        webView.getSettings().setDatabaseEnabled(true);
        webView.getSettings().setDomStorageEnabled(true);//DOM Storage
        webView.requestFocus();
        webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);

        //跳转到商品详情
        webView.registerHandler("goods_detail", new BridgeHandler() {
                    @Override
                    public void handler(String s, CallBackFunction callBackFunction) {
                        try {
                            if(s==null){
                                LogUtils.e("goods_detail","空");
                            }else {
                                LogUtils.e("goods_detail",s);
                            }
                            LogUtils.e("goods_detail", URLDecoder.decode(s.toString(), "utf-8"));
                            JSONObject json = new JSONObject(URLDecoder.decode(s.toString(), "utf-8"));
                            String goods_id = json.optString("goods_id");
                            String type = json.optString("type");
                            if (!ViewUtils.isEmpty(goods_id)) {
                                if (TextUtils.equals("register", goods_id)) {
                                    Intent intent = new Intent(getActivity(), RegisterAccount.class);
                                    startActivity(intent);
                                } else if (type.equals("1")) {
                                    startActivity(new Intent(getActivity(), FastGoodsDetailActivity.class).putExtra("id", goods_id));
                                }else {
                                    startActivity(new Intent(getActivity(), ProductInfoActivity.class).putExtra("goods_id", goods_id));
                                }
                            } else
                                ToastUtils.showToast("商品不存在");
                        } catch (
                                JSONException e
                                )

                        {
                            e.printStackTrace();
                        } catch (
                                UnsupportedEncodingException e
                                )

                        {
                            e.printStackTrace();
                        }
                    }
                }

        );



        //跳转到商品列表页
        webView.registerHandler("goods_list", new

                BridgeHandler() {
                    @Override
                    public void handler(String s, CallBackFunction callBackFunction) {
                        try {
                            LogUtils.e("goods_list", URLDecoder.decode(s.toString(), "utf-8"));
                            JSONObject json = new JSONObject(URLDecoder.decode(s.toString(), "utf-8"));

                            String name = json.optString("title");
                            String keywords = json.optString("keywords");
                            String cate_id = json.optString("cate_id");
                            String brand_id = json.optString("brand_id");
                            String is_new = json.optString("is_new");
                            if (!(ViewUtils.isEmpty(cate_id) && ViewUtils.isEmpty(brand_id))) {
                                startActivity(new Intent(getActivity(), BrandInfoActivity.class)
                                        .putExtra("name", name)
                                        .putExtra("keywords", keywords)
                                        .putExtra("cate_id", cate_id)
                                        .putExtra("brand_id", brand_id)
                                        .putExtra("is_new", is_new));
                            }
                            if (ViewUtils.isEmpty(cate_id) && ViewUtils.isEmpty(brand_id)){
                                Intent intent = new Intent(getActivity(), MeiQiFastBuyActivity.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(intent);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }
                }

        );


        //跳转到商品列表页
        webView.registerHandler("presale_goods_list", new

                BridgeHandler() {
                    @Override
                    public void handler(String s, CallBackFunction callBackFunction) {
                        try {
                            LogUtils.e("presale_goods_list", URLDecoder.decode(s.toString(), "utf-8"));
                            JSONObject json = new JSONObject(URLDecoder.decode(s.toString(), "utf-8"));
                            String cate_id = json.optString("cate_id");
                            if (!TextUtils.isEmpty(cate_id)) {
                                Intent intent = new Intent(getActivity(), MeiQiFastBuyActivity.class);
//                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                               intent.putExtra( "cate_id",cate_id);
                                startActivity(intent);
                            }
                            if (ViewUtils.isEmpty(cate_id)){
                                Intent intent = new Intent(getActivity(), MeiQiFastBuyActivity.class);
//                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(intent);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }
                }

        );

        webView.registerHandler("preview_goods_img", new BridgeHandler() {
            @Override
            public void handler(String s, CallBackFunction function) {
                try {
                    JSONObject json = new JSONObject(URLDecoder.decode(s.toString(), "utf-8"));
                    int show_index = json.optInt("show_index");
                    JSONArray img_list = json.optJSONArray("img_list");
                    ArrayList<String> imgs = new ArrayList
                            <String>();
                    for (int i = 0; i < img_list.length(); i++) {
                        JSONObject jsonObject = img_list.optJSONObject(i);
                        String url = jsonObject.optString("url");
                        imgs.add(url);
                    }
                    Intent intent = new Intent(getActivity(),ActivityPhotoView.class);
                    Bundle bundle1 = new Bundle();
                    bundle1.putString("index",show_index+"");
                    bundle1.putStringArrayList("imgs",imgs);
                    intent.putExtra("bundle",bundle1);
                    startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });

    }

    @Override
    public void onPause() {
        super.onPause();
        webView.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        webView.onResume();
    }



    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
        getActivity().deleteDatabase("WebView.db");
        getActivity().deleteDatabase("WebViewCache.db");
    }
}
